Completed
Push — master ( dc5d8d...004bed )
by Dongxin
41s
created

common.js ➔ isJSON   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
cc 5
c 3
b 0
f 1
nc 5
nop 1
dl 0
loc 12
rs 8.8571
1
// Copyright © 2017 Tangdongxin
2
3
// Permission is hereby granted, free of charge, to any person obtaining
4
// a copy of this software and associated documentation files (the "Software"),
5
// to deal in the Software without restriction, including without limitation
6
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7
// and/or sell copies of the Software, and to permit persons to whom the
8
// Software is furnished to do so, subject to the following conditions:
9
// The above copyright notice and this permission notice shall be included
10
// in all copies or substantial portions of the Software.
11
12
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
14
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
15
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
17
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
18
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
20
21
var bgColor; // background color
0 ignored issues
show
Unused Code introduced by
The variable bgColor seems to be never used. Consider removing it.
Loading history...
22
var intColor; // integer color
0 ignored issues
show
Unused Code introduced by
The variable intColor seems to be never used. Consider removing it.
Loading history...
23
var strColor; // string color
0 ignored issues
show
Unused Code introduced by
The variable strColor seems to be never used. Consider removing it.
Loading history...
24
var keyColor; // k-v key color
0 ignored issues
show
Unused Code introduced by
The variable keyColor seems to be never used. Consider removing it.
Loading history...
25
var defaultColor; // default text color
0 ignored issues
show
Unused Code introduced by
The variable defaultColor seems to be never used. Consider removing it.
Loading history...
26
var fontStyle; // font-family
0 ignored issues
show
Unused Code introduced by
The variable fontStyle seems to be never used. Consider removing it.
Loading history...
27
var fontSize; // font-size
0 ignored issues
show
Unused Code introduced by
The variable fontSize seems to be never used. Consider removing it.
Loading history...
28
var strictOnly; // only deal with the application/json response
0 ignored issues
show
Unused Code introduced by
The variable strictOnly seems to be never used. Consider removing it.
Loading history...
29
var hideDetails; // hide the count and size
30
var dontBeatify; // hide the [str] or [json]
0 ignored issues
show
Unused Code introduced by
The variable dontBeatify seems to be never used. Consider removing it.
Loading history...
31
var strLength; // string length
0 ignored issues
show
Unused Code introduced by
The variable strLength seems to be never used. Consider removing it.
Loading history...
32
var isDebug; // debug mode
33
// ===========================================
34
// DEFAULT VALUES
35
// ===========================================
36
var RAND = "MIKE";
37
var HOV  = "H" + RAND;
38
var DIV  = "D" + RAND;
39
var KEY  = "K" + RAND;
40
var STR  = "S" + RAND;
41
var BOOL = "B" + RAND;
42
var ERR  = "E" + RAND;
43
var COLL = "C" + RAND;
44
45
// ===========================================
46
// COMMON FUNCTIONS
47
// ===========================================
48
function onError(result, error) {
0 ignored issues
show
Unused Code introduced by
The parameter error is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
49
    console.log(result);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
50
}
51
52
function dlog(target) {
53
    if (isDebug) {
0 ignored issues
show
Bug introduced by
The variable isDebug seems to be never initialized.
Loading history...
54
        console.log(target);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
55
    }
56
}
57
58
function reconvert(str) {
59
    str = str.replace(/(\\u)(\w{1,4})/gi, function($0) {
60
        return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{1,4})/g, "$2")), 16)));
61
    });
62
    str = str.replace(/(&#x)(\w{1,4});/gi, function($0) {
63
        return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{1,4})(%3B)/g, "$2"), 16));
64
    });
65
    str = str.replace(/(&#)(\d{1,6});/gi, function($0) {
66
        return String.fromCharCode(parseInt(escape($0).replace(/(%26%23)(\d{1,6})(%3B)/g, "$2")));
67
    });
68
69
    return str;
70
}
71
72
function units(size) {
73
    return size > 1048576 ? (0 | (size / 1048576)) + "MB" :
74
        size > 1024 ? (0 | (size / 1024)) + "KB" :
75
        size + "B";
76
}
77
78
function fragment(div, a, b) {
79
    var frag = document.createDocumentFragment();
80
    frag.appendChild(document.createTextNode(a));
81
    if (b) {
82
        frag.appendChild(div.cloneNode());
83
        frag.appendChild(document.createTextNode(b));
84
    } else {
85
        frag.appendChild(document.createElement("br"));
86
    }
87
    return frag;
88
}
89
90
function change(node, query, name, set) {
91
    var list = node.querySelectorAll(query),
92
        i = list.length;
93
    for (; i--;) list[i].classList[set ? "add" : "remove"](name);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
94
}
95
96
function draw(str, current, isEmbed = false) {
97
    var re = /("(?:((?:https?|file):\/\/(?:\\?\S)+?)|(?:\\?.)*?)")\s*(:?)|-?\d+\.?\d*(?:e[+-]?\d+)?|true|false|null|[[\]{},]|(\S[^-[\]{},"\d]*)/gi;
98
    var node = document.createElement("div");
99
    node.classList.add(DIV);
100
    var link = document.createElement("a");
101
    var span = document.createElement("span");
102
    var info = document.createElement("i");
103
    var colon = document.createTextNode(": ");
104
    var comma = fragment(node, ",");
105
    var path = [];
106
    var cache = {
107
        "{": fragment(node, "{", "}"),
108
        "[": fragment(node, "[", "]")
109
    };
110
111
    node.className = "R" + RAND;
112
    link.classList.add("L" + RAND);
113
    if (isEmbed) {
114
        info.classList.add("IJSON" + RAND);
115
    } else {
116
        info.classList.add("I" + RAND);
117
    }
118
119
    parse(str, re);
120
121
    current.innerHTML = node.innerHTML;
122
123
    function parse(str, re) {
124
        str = reconvert(str);
125
        var match, val, tmp, i = 0;
0 ignored issues
show
Unused Code introduced by
The variable i seems to be never used. Consider removing it.
Loading history...
126
        var len = str.length;
127
        try {
128
            for (; match = re.exec(str);) {
129
                val = match[0];
130
                if (val == "{" || val == "[") {
131
                    path.push(node);
0 ignored issues
show
Bug introduced by
The variable node is changed as part of the for loop for example by node.lastChild.previousSibling on line 133. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
132
                    node.appendChild(cache[val].cloneNode(true));
133
                    node = node.lastChild.previousSibling;
134
                    node.len = 1;
135
                    node.start = re.lastIndex;
136
                } else if ((val == "}" || val == "]") && node.len) {
137
                    if (node.childNodes.length) {
138
                        tmp = info.cloneNode();
139
                        var content = node.len + (
140
                            node.len == 1 ?
141
                            (val == "]" ? " item, " : " property, ") :
142
                            (val == "]" ? " items, " : " properties, ")
143
                        ) + units(re.lastIndex - node.start + 1);
144
145
                        if (hideDetails) {
146
                            tmp.setAttribute("title", content);
147
                        } else {
148
                            tmp.dataset.content = content;
149
                        }
150
151
                        if ((val = node.previousElementSibling) && val.className == KEY) {
152
                            tmp.dataset.key = reconvert(val.textContent.slice(1, -1).replace(/'/, "\\'"));
153
                        }
154
                        node.parentNode.insertBefore(tmp, node);
155
                    } else {
156
                        node.parentNode.removeChild(node);
157
                    }
158
                    node = path.pop();
159
                } else if (val == ",") {
160
                    node.len += 1;
161
                    node.appendChild(comma.cloneNode(true));
162
                } else {
163
                    tmp = span.cloneNode();
164
                    tmp.textContent = match[1] || val;
165
                    tmp.classList.add(match[3] ? KEY : match[1] ? STR : match[4] ? ERR : BOOL);
166
                    node.appendChild(tmp);
167
                    if (match[3]) {
168
                        node.appendChild(colon.cloneNode());
169
                    }
170
                }
171
            }
172
            document.title = "";
173
            JSON.parse(str);
174
        } catch (e) {
175
            dlog(e);
176
            // TODO: find a better way to report error
177
        }
178
    }
179
}
180
181
function isJSON(str) {
182
    if (typeof str == 'string') {
183
        try {
184
            var obj = JSON.parse(str);
185
            if (JSON.stringify(obj).indexOf('{') == 1 ||
186
                JSON.stringify(obj).indexOf(']') == 1) {
187
                return true;
188
            }
189
        } catch (e) {}
0 ignored issues
show
Coding Style Comprehensibility Best Practice introduced by
Empty catch clauses should be used with caution; consider adding a comment why this is needed.
Loading history...
190
    }
191
    return false;
192
}
193